use std::fs;

use rfd::FileDialog;
use slint::{ComponentHandle, LogicalPosition, PlatformError};

use crate::App;
use crate::tools::read_formal;

pub fn work() -> Result<(), PlatformError> {
    let ui = App::new()?;

    let ui_handle = ui.as_weak();
    ui.on_set_filepath(move || {
        let ui = ui_handle.unwrap();
        let filepath = select_file();
        if filepath.len() > 0 {
            ui.set_label_file(filepath.into());
        }
    });

    let ui_handle = ui.as_weak();
    ui.on_out_save(move || {
        let ui = ui_handle.unwrap();
        let label_out = ui.get_label_out().to_string();
        println!("Save Check");
        if label_out.len() > 0 {
            let filepath = save_file(label_out);
            ui.set_label_title(format!("{filepath}").into())
        }
    });

    let ui_handle = ui.as_weak();
    ui.on_out_value(move || {
        let ui = ui_handle.unwrap();
        let file = ui.get_label_file().to_string();
        let start = ui.get_label_start().to_string();
        let end = ui.get_label_end().to_string();
        let label_value = read_formal::read_csv(file, (start, end));
        ui.set_label_out(label_value.into());
        ui.set_label_title("输出结果".into());
        ui.set_window_hight(400.0)
    });

    // *****************窗口操作*****************
    let ui_handle = ui.as_weak();
    ui.on_close_window(move || {
        let ui = ui_handle.unwrap();
        ui.hide().unwrap();
    });

    let ui_handle = ui.as_weak();
    ui.on_move_window(move |offset_x, offset_y| {
        let ui = ui_handle.unwrap();
        //获取窗口的物理坐标
        let logical_pos = ui.window().position().to_logical(ui.window().scale_factor());
        println!("{} {} {} {}", logical_pos.x, logical_pos.y, offset_x, offset_y);
        //窗口坐标添加上偏移量，设置为新的位置
        ui.window().set_position(LogicalPosition::new(logical_pos.x + offset_x, logical_pos.y + offset_y));
    });
    // *****************窗口操作*****************
    ui.run()
}

fn select_file() -> String {
    let file = FileDialog::new()
        .add_filter("文件", &["csv", "txt"])
        .set_directory("/")
        .pick_file();
    let path = match file {
        Some(f) => {
            println!("读取文件成功");
            f.as_path().to_str().unwrap().to_string()
        }
        None => {
            println!("读取文件失败");
            "".to_string()
        }
    };
    println!("{path}");
    path
}

fn select_save() -> String {
    let file = FileDialog::new()
        .add_filter("TXT", &["txt"])
        .set_file_name("out")
        .save_file();
    println!("Save Select");
    match file {
        Some(f) => {
            println!("选择文件");
            f.as_path().to_str().unwrap().to_string()
        }
        None => {
            println!("quit save");
            "".to_string()
        }
    }
}

fn save_file(value: String) -> String {
    let filepath = select_save();
    match fs::write(filepath.clone(), value) {
        Ok(_) => {
            format!("{filepath}")
        }
        Err(e) => {
            eprint!("Save Failed {e}");
            String::from("Save Failed")
        }
    }
}